package com.anttribe.components.infra.lang.reflect;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;

import com.google.common.collect.Lists;

/**
 * @author zhaoyong
 * @date 2021/9/21 0021
 */
public final class ReflectUtils {

    /**
     * 获取指定class的包名
     *
     * @param clazz
     *            Class<?>
     * @return String
     */
    public static String getPackageName(Class<?> clazz) {
        return clazz.getPackage().getName();
    }

    /**
     * 获取类实现的接口上所有的泛型类型
     * 
     * @param clazz
     *            Class<?>
     * @return List<Class<?>>
     */
    public static List<Class<?>> getGenericInterfacesParameterizedTypes(Class<?> clazz) {
        List<Class<?>> genericInterfacesParameterizedTypes = Lists.newArrayList();
        if (null != clazz && ArrayUtils.isNotEmpty(clazz.getGenericInterfaces())) {
            Type[] geneticInterfaces = clazz.getGenericInterfaces();
            for (Type geneticInterface : geneticInterfaces) {
                if (!(geneticInterface instanceof ParameterizedType)) {
                    continue;
                }

                Type[] actualTypeArguments = ((ParameterizedType)geneticInterface).getActualTypeArguments();
                if (ArrayUtils.isEmpty(actualTypeArguments)) {
                    continue;
                }

                for (Type actualTypeArgument : actualTypeArguments) {
                    genericInterfacesParameterizedTypes.add((Class<?>)actualTypeArgument);
                }
            }
        }

        return genericInterfacesParameterizedTypes;
    }

}
